package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class UpDownListener {

    @Autowired
    private IApArticleService apArticleService;


    // 指定监听主题
    @KafkaListener(topics = "${topic.upDownTopic}")
    public void handleMessage(ConsumerRecord<String,String> record){
        String value = record.value();
        if (StringUtils.isNotEmpty(value)) {
            //解析获取的map
            HashMap map = JSON.parseObject(value, HashMap.class);
            Long articleId = (Long) map.get("articleId");
            boolean isDown = (boolean) map.get("isDown");

            // 更新文章表状态
            LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticle::getId, articleId);
            updateWrapper.set(ApArticle::getIsDown, isDown);

            apArticleService.update(updateWrapper);
        }
    }

}
